/**
 * 国际化错误信息管理系统
 * 为每个页面提供独立的错误提示命名空间，避免文案串用
 */

// 当前语言状态
let currentLanguage = localStorage.getItem('admin_language') || 'zh';

// 语言切换函数
export const switchLanguage = () => {
  currentLanguage = currentLanguage === 'zh' ? 'en' : 'zh';
  localStorage.setItem('admin_language', currentLanguage);
  // 触发页面刷新以应用新语言
  window.location.reload();
};

export const getCurrentLanguage = () => currentLanguage;

// 通用错误信息
const COMMON_ERRORS = {
  zh: {
    NETWORK_ERROR: '网络连接异常，请检查网络设置',
    UNAUTHORIZED: '登录已过期，请重新登录',
    FORBIDDEN: '权限不足，无法执行此操作',
    SERVER_ERROR: '服务器内部错误，请稍后重试',
    UNKNOWN_ERROR: '未知错误，请联系管理员'
  },
  en: {
    NETWORK_ERROR: 'Network connection error, please check your network settings',
    UNAUTHORIZED: 'Login expired, please log in again',
    FORBIDDEN: 'Insufficient permissions to perform this operation',
    SERVER_ERROR: 'Internal server error, please try again later',
    UNKNOWN_ERROR: 'Unknown error, please contact administrator'
  }
};

// 界面文本翻译
export const UI_TEXTS = {
  zh: {
    // 导航菜单
    dashboard: '仪表盘',
    userManagement: '用户管理',
    menuManagement: '菜单管理',
    orderManagement: '订单管理',
    couponManagement: '优惠券管理',
    socialReview: '社交媒体评价',
    inviteManagement: '邀请管理',
    reportsAnalysis: '报表分析',
    systemManagement: '系统管理',
    adminPanel: '管理后台',
    standardAdminPanel: '标准管理后台',
    
    // 菜单管理相关
    dishName: '菜品名称',
    category: '分类',
    price: '售价',
    originalPrice: '原价',
    stock: '库存',
    description: '描述',
    ingredients: '配料',
    status: '状态',
    hotDish: '热门菜品',
    newDish: '新品推荐',
    dishImage: '菜品图片',
    editDish: '编辑菜品',
    addDish: '添加菜品',
    save: '保存',
    cancel: '取消',
    confirm: '确定',
    delete: '删除',
    
    // 状态选项
    available: '可售',
    unavailable: '缺货',
    hidden: '隐藏',
    yes: '是',
    no: '否',
    
    // 表单提示
    enterDishName: '请输入菜品名称',
    selectCategory: '请选择分类',
    enterPrice: '请输入售价',
    enterOriginalPrice: '请输入原价',
    enterStock: '请输入库存',
    enterDescription: '请输入菜品描述',
    enterIngredients: '请输入菜品配料信息（可选）',
    selectStatus: '请选择状态',
    uploadImage: '上传图片',
    clickUpload: '点击上传',
    
    // 报表相关
    salesReports: '销售报表',
    userReports: '用户报表',
    financialReports: '财务报表',
    dailySalesReport: '日销售报表',
    monthlySalesReport: '月销售报表',
    productSalesReport: '产品销售报表',
    userGrowthReport: '用户增长报表',
    userActivityReport: '用户活跃度报表',
    userRetentionReport: '用户留存报表',
    revenueReport: '收入报表',
    costReport: '成本报表',
    profitReport: '利润报表',
    taxReport: '税务报表'
  },
  en: {
    // Navigation menu
    dashboard: 'Dashboard',
    userManagement: 'User Management',
    menuManagement: 'Menu Management',
    orderManagement: 'Order Management',
    couponManagement: 'Coupon Management',
    socialReview: 'Social Media Review',
    inviteManagement: 'Invite Management',
    reportsAnalysis: 'Reports & Analytics',
    systemManagement: 'System Management',
    adminPanel: 'Admin Panel',
    standardAdminPanel: 'Standard Admin Panel',
    
    // Menu management related
    dishName: 'Dish Name',
    category: 'Category',
    price: 'Price',
    originalPrice: 'Original Price',
    stock: 'Stock',
    description: 'Description',
    ingredients: 'Ingredients',
    status: 'Status',
    hotDish: 'Hot Dish',
    newDish: 'New Dish',
    dishImage: 'Dish Image',
    editDish: 'Edit Dish',
    addDish: 'Add Dish',
    save: 'Save',
    cancel: 'Cancel',
    confirm: 'Confirm',
    delete: 'Delete',
    
    // Status options
    available: 'Available',
    unavailable: 'Out of Stock',
    hidden: 'Hidden',
    yes: 'Yes',
    no: 'No',
    
    // Form prompts
    enterDishName: 'Please enter dish name',
    selectCategory: 'Please select category',
    enterPrice: 'Please enter price',
    enterOriginalPrice: 'Please enter original price',
    enterStock: 'Please enter stock',
    enterDescription: 'Please enter dish description',
    enterIngredients: 'Please enter ingredients (optional)',
    selectStatus: 'Please select status',
    uploadImage: 'Upload Image',
    clickUpload: 'Click to Upload',
    
    // Reports related
    salesReports: 'Sales Reports',
    userReports: 'User Reports',
    financialReports: 'Financial Reports',
    dailySalesReport: 'Daily Sales Report',
    monthlySalesReport: 'Monthly Sales Report',
    productSalesReport: 'Product Sales Report',
    userGrowthReport: 'User Growth Report',
    userActivityReport: 'User Activity Report',
    userRetentionReport: 'User Retention Report',
    revenueReport: 'Revenue Report',
    costReport: 'Cost Report',
    profitReport: 'Profit Report',
    taxReport: 'Tax Report'
  }
};

// 获取UI文本的函数
export const t = (key) => {
  const keys = key.split('.');
  let value = UI_TEXTS[currentLanguage];
  
  for (const k of keys) {
    value = value?.[k];
  }
  
  return value || key;
};

// 页面特定错误信息
const PAGE_ERRORS = {
  // 用户管理页面
  USERS: {
    DELETE_FAILED: '用户删除失败，请检查用户是否存在关联数据',
    UPDATE_FAILED: '用户信息更新失败，请检查输入数据格式',
    SAVE_FAILED: '用户信息保存失败，请检查必填字段',
    STATUS_UPDATE_FAILED: '用户状态更新失败，请稍后重试',
    LOAD_FAILED: '用户列表加载失败，请刷新页面重试'
  },
  
  // 菜单管理页面
  MENU: {
    SAVE_FAILED: '菜品信息保存失败，请检查图片格式和必填字段',
    DELETE_FAILED: '菜品删除失败，请检查是否存在关联订单',
    UPDATE_FAILED: '菜品信息更新失败，请检查价格格式',
    LOAD_FAILED: '菜单数据加载失败，请检查网络连接',
    IMAGE_UPLOAD_FAILED: '菜品图片上传失败，请检查图片大小和格式'
  },
  
  // 订单管理页面
  ORDERS: {
    STATUS_UPDATE_FAILED: '订单状态更新失败，请检查订单当前状态',
    LOAD_FAILED: '订单列表加载失败，请刷新页面',
    DELETE_FAILED: '订单删除失败，已完成订单无法删除',
    EXPORT_FAILED: '订单导出失败，请检查数据权限'
  },
  
  // 优惠券管理页面
  COUPONS: {
    SAVE_FAILED: '优惠券保存失败，请检查有效期和折扣设置',
    DELETE_FAILED: '优惠券删除失败，已使用的优惠券无法删除',
    UPDATE_FAILED: '优惠券更新失败，请检查优惠规则设置',
    LOAD_FAILED: '优惠券列表加载失败，请重试'
  },
  
  // 邀请管理页面
  INVITES: {
    LOAD_FAILED: '邀请数据加载失败，请检查API连接',
    STATS_LOAD_FAILED: '邀请统计数据加载失败，请刷新页面',
    EXPORT_FAILED: '邀请记录导出失败，请检查数据权限',
    ISSUE_FAILED: '礼券发放失败，请检查邀请记录状态'
  },
  
  // 系统设置页面
  SYSTEM: {
    SAVE_FAILED: '系统设置保存失败，请检查配置参数格式',
    DELETE_FAILED: '配置删除失败，系统必需配置无法删除',
    LOAD_FAILED: '系统配置加载失败，请联系管理员',
    BACKUP_FAILED: '数据备份失败，请检查存储空间'
  },
  
  // 仪表板页面
  DASHBOARD: {
    LOAD_FAILED: '仪表板数据加载失败，请刷新页面查看最新数据',
    CHART_RENDER_FAILED: '图表渲染失败，请检查数据格式',
    STATS_LOAD_FAILED: '统计数据加载失败，请稍后重试'
  },
  
  // 登录页面
  LOGIN: {
    AUTH_FAILED: '登录验证失败，请检查用户名和密码',
    TOKEN_EXPIRED: '登录令牌已过期，请重新登录',
    LOAD_FAILED: '登录页面加载失败，请检查系统状态'
  },

  // 社交媒体审核页面
  SOCIAL_REVIEW: {
    STATS_LOAD_FAILED: '获取统计数据失败，请刷新页面重试',
    SUBMISSIONS_LOAD_FAILED: '获取提交记录失败，请检查网络连接',
    EXPORT_FAILED: '导出失败，请检查数据权限',
    REVIEW_FAILED: '审核失败，请稍后重试',
    BATCH_REVIEW_FAILED: '批量审核时发生错误，请检查选择项目',
    FORM_VALIDATION_FAILED: '请完成所有必填项再提交'
  },

  // 报表页面
  REPORTS: {
    LOAD_FAILED: '获取报表数据失败，请检查网络连接',
    EXPORT_FAILED: '报表导出失败，请检查数据权限'
  },

  // 系统管理页面 - 额外错误
  SYSTEM_EXTRA: {
    RESTART_FAILED: '系统重启失败，请检查服务状态',
    DOWNLOAD_FAILED: '备份文件下载失败，请稍后重试',
    DELETE_FAILED: '备份文件删除失败，请检查权限'
  },

  // 订单管理页面 - 额外错误
  ORDERS_EXTRA: {
    LOAD_FAILED: '获取订单数据失败，请检查网络连接',
    STATS_LOAD_FAILED: '获取订单统计数据失败，请稍后重试',
    EXPORT_FAILED: '订单导出失败，请检查数据权限'
  }
};

// 成功信息
const SUCCESS_MESSAGES = {
  USERS: {
    SAVE_SUCCESS: '用户信息保存成功',
    DELETE_SUCCESS: '用户删除成功',
    UPDATE_SUCCESS: '用户信息更新成功',
    STATUS_UPDATE_SUCCESS: '用户状态更新成功'
  },
  
  MENU: {
    SAVE_SUCCESS: '菜品信息保存成功',
    DELETE_SUCCESS: '菜品删除成功',
    UPDATE_SUCCESS: '菜品信息更新成功'
  },
  
  ORDERS: {
    STATUS_UPDATE_SUCCESS: '订单状态更新成功',
    EXPORT_SUCCESS: '订单导出成功'
  },
  
  COUPONS: {
    SAVE_SUCCESS: '优惠券保存成功',
    DELETE_SUCCESS: '优惠券删除成功',
    UPDATE_SUCCESS: '优惠券更新成功'
  },
  
  SYSTEM: {
    SAVE_SUCCESS: '系统设置保存成功',
    BACKUP_SUCCESS: '数据备份成功'
  },

  INVITES: {
    ISSUE_SUCCESS: '礼券发放成功！'
  },

  SOCIAL_REVIEW: {
    EXPORT_SUCCESS: '导出成功',
    REVIEW_SUCCESS: '审核成功'
  },

  REPORTS: {
    EXPORT_SUCCESS: '报表导出成功'
  },

  // 系统管理页面成功消息 - 额外
  SYSTEM_EXTRA: {
    RESTART_SUCCESS: '系统重启完成',
    DOWNLOAD_SUCCESS: '备份文件下载成功',
    DELETE_SUCCESS: '备份文件删除成功'
  },

  // 订单管理页面成功消息 - 额外
  ORDERS_EXTRA: {
    EXPORT_SUCCESS: '订单导出成功'
  }
};

/**
 * 获取错误信息
 * @param {string} page - 页面名称 (USERS, MENU, ORDERS, etc.)
 * @param {string} errorType - 错误类型
 * @param {string} fallback - 备用错误信息
 * @returns {string} 错误信息
 */
export function getErrorMessage(page, errorType, fallback) {
  const lang = currentLanguage;
  const defaultFallback = COMMON_ERRORS[lang]?.UNKNOWN_ERROR || 'Unknown error';
  
  if (COMMON_ERRORS[lang] && COMMON_ERRORS[lang][errorType]) {
    return COMMON_ERRORS[lang][errorType];
  }
  
  if (PAGE_ERRORS[page] && PAGE_ERRORS[page][errorType]) {
    return PAGE_ERRORS[page][errorType];
  }
  
  return fallback || defaultFallback;
}

/**
 * 获取成功信息
 * @param {string} page - 页面名称
 * @param {string} successType - 成功类型
 * @param {string} fallback - 备用成功信息
 * @returns {string} 成功信息
 */
export function getSuccessMessage(page, successType, fallback = '操作成功') {
  if (SUCCESS_MESSAGES[page] && SUCCESS_MESSAGES[page][successType]) {
    return SUCCESS_MESSAGES[page][successType];
  }
  
  return fallback;
}

/**
 * 根据HTTP状态码获取通用错误信息
 * @param {number} statusCode - HTTP状态码
 * @returns {string} 错误信息
 */
export function getHttpErrorMessage(statusCode) {
  switch (statusCode) {
    case 401:
      return COMMON_ERRORS.UNAUTHORIZED;
    case 403:
      return COMMON_ERRORS.FORBIDDEN;
    case 404:
      return '请求的资源不存在';
    case 500:
      return COMMON_ERRORS.SERVER_ERROR;
    case 502:
    case 503:
    case 504:
      return '服务暂时不可用，请稍后重试';
    default:
      if (statusCode >= 400 && statusCode < 500) {
        return '请求参数错误，请检查输入信息';
      } else if (statusCode >= 500) {
        return COMMON_ERRORS.SERVER_ERROR;
      }
      return COMMON_ERRORS.NETWORK_ERROR;
  }
}

/**
 * 页面常量，避免硬编码
 */
export const PAGES = {
  USERS: 'USERS',
  MENU: 'MENU',
  ORDERS: 'ORDERS',
  COUPONS: 'COUPONS',
  INVITES: 'INVITES',
  SYSTEM: 'SYSTEM',
  DASHBOARD: 'DASHBOARD',
  LOGIN: 'LOGIN',
  INVITE_MANAGEMENT: 'INVITE_MANAGEMENT',
  SOCIAL_REVIEW: 'SOCIAL_REVIEW',
  REPORTS: 'REPORTS',
  SYSTEM_EXTRA: 'SYSTEM_EXTRA',
  ORDERS_EXTRA: 'ORDERS_EXTRA'
};

/**
 * 错误类型常量
 */
export const ERROR_TYPES = {
  SAVE_FAILED: 'SAVE_FAILED',
  DELETE_FAILED: 'DELETE_FAILED',
  UPDATE_FAILED: 'UPDATE_FAILED',
  LOAD_FAILED: 'LOAD_FAILED',
  STATUS_UPDATE_FAILED: 'STATUS_UPDATE_FAILED',
  EXPORT_FAILED: 'EXPORT_FAILED',
  ISSUE_FAILED: 'ISSUE_FAILED',
  STATS_LOAD_FAILED: 'STATS_LOAD_FAILED',
  SUBMISSIONS_LOAD_FAILED: 'SUBMISSIONS_LOAD_FAILED',
  REVIEW_FAILED: 'REVIEW_FAILED',
  BATCH_REVIEW_FAILED: 'BATCH_REVIEW_FAILED',
  FORM_VALIDATION_FAILED: 'FORM_VALIDATION_FAILED',
  REPORT_LOAD_FAILED: 'REPORT_LOAD_FAILED',
  REPORT_EXPORT_FAILED: 'REPORT_EXPORT_FAILED',
  SYSTEM_RESTART_FAILED: 'SYSTEM_RESTART_FAILED',
  SYSTEM_DOWNLOAD_FAILED: 'SYSTEM_DOWNLOAD_FAILED',
  SYSTEM_DELETE_FAILED: 'SYSTEM_DELETE_FAILED',
  ORDER_LOAD_FAILED: 'ORDER_LOAD_FAILED',
  ORDER_STATS_LOAD_FAILED: 'ORDER_STATS_LOAD_FAILED',
  ORDER_EXPORT_FAILED: 'ORDER_EXPORT_FAILED',
  NETWORK_ERROR: 'NETWORK_ERROR',
  UNAUTHORIZED: 'UNAUTHORIZED',
  FORBIDDEN: 'FORBIDDEN',
  SERVER_ERROR: 'SERVER_ERROR'
};

/**
 * 成功类型常量
 */
export const SUCCESS_TYPES = {
  SAVE_SUCCESS: 'SAVE_SUCCESS',
  DELETE_SUCCESS: 'DELETE_SUCCESS',
  UPDATE_SUCCESS: 'UPDATE_SUCCESS',
  STATUS_UPDATE_SUCCESS: 'STATUS_UPDATE_SUCCESS',
  EXPORT_SUCCESS: 'EXPORT_SUCCESS',
  ISSUE_SUCCESS: 'ISSUE_SUCCESS',
  REVIEW_SUCCESS: 'REVIEW_SUCCESS',
  REPORT_EXPORT_SUCCESS: 'REPORT_EXPORT_SUCCESS',
  SYSTEM_RESTART_SUCCESS: 'SYSTEM_RESTART_SUCCESS',
  SYSTEM_DOWNLOAD_SUCCESS: 'SYSTEM_DOWNLOAD_SUCCESS',
  SYSTEM_DELETE_SUCCESS: 'SYSTEM_DELETE_SUCCESS',
  ORDER_EXPORT_SUCCESS: 'ORDER_EXPORT_SUCCESS'
};